package mya_dc.client.gui;

import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import mya_dc.client.core.ClientSettings;
import mya_dc.client.core.CompilationClient;
import mya_dc.client.gui.TextMessages.EMessageBoxType;
import mya_dc.shared_classes.MYA_File;
import mya_dc.shared_classes.gui.SharedComponents;

/**
 * The new project wizard used in the compilation client
 * 
 * @author      Adam Levi
 * <br>			MYA
 */
public class NewProjectWizard extends JDialog
{
	private static final long serialVersionUID = -4754373525722253816L;
	private JCheckBox autoTransferCheckBox;
	private JTextField outputFileTextField;
	private JTextField portNumberTextField;
	private JTextField hostNameTextField;
	private JCheckBox savepasswordCheckBox;
	private JTextField projectHomeDirTextField;
	private JTextField projectNameTextField;
	private JPasswordField passwordTextField;
	private JTextField userNameTextField;

	/**
	 * Create the dialog
	 */
	public NewProjectWizard() {
		super();
		setTitle("New Project Wizard");
		getContentPane().setLayout(null);
		setBounds(100, 100, 478, 431);

		final JButton okButton = new JButton();
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				doOK();
			}
		});
		okButton.setText("OK");
		okButton.setBounds(367, 364, 90, 23);
		getContentPane().add(okButton);

		final JPanel authenticationPanel = new JPanel();
		authenticationPanel.setBorder(new TitledBorder(null, "Authentication", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, SystemColor.activeCaption));
		authenticationPanel.setLayout(null);
		authenticationPanel.setBounds(10, 10, 447, 117);
		getContentPane().add(authenticationPanel);

		savepasswordCheckBox = new JCheckBox();
		savepasswordCheckBox.setSelected(true);
		savepasswordCheckBox.setText("Remember Password");
		savepasswordCheckBox.setBounds(253, 49, 125, 23);
		authenticationPanel.add(savepasswordCheckBox);

		final JLabel projectNameLabel_1 = new JLabel();
		projectNameLabel_1.setBounds(26, 21, 91, 24);
		authenticationPanel.add(projectNameLabel_1);
		projectNameLabel_1.setText("User Name:");

		userNameTextField = new JTextField();
		userNameTextField.setBounds(123, 23, 124, 21);
		authenticationPanel.add(userNameTextField);
		userNameTextField.setText("AdamLevi");

		final JLabel projectNameLabel_1_1 = new JLabel();
		projectNameLabel_1_1.setBounds(26, 48, 91, 24);
		authenticationPanel.add(projectNameLabel_1_1);
		projectNameLabel_1_1.setText("Password:");

		passwordTextField = new JPasswordField();
		passwordTextField.setBounds(123, 50, 124, 21);
		authenticationPanel.add(passwordTextField);
		passwordTextField.setText("pass");

		final JLabel projectNameLabel = new JLabel();
		projectNameLabel.setBounds(26, 78, 91, 24);
		authenticationPanel.add(projectNameLabel);
		projectNameLabel.setText("Project Name:");

		projectNameTextField = new JTextField();
		projectNameTextField.setBounds(123, 80, 124, 21);
		authenticationPanel.add(projectNameTextField);
		projectNameTextField.setText("MYA_Project");

		final JPanel connectionPanel = new JPanel();
		connectionPanel.setBorder(new TitledBorder(null, "Connection", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, SystemColor.activeCaption));
		connectionPanel.setLayout(null);
		connectionPanel.setBounds(10, 241, 447, 117);
		getContentPane().add(connectionPanel);

		final JLabel hostipAddressLabel = new JLabel();
		hostipAddressLabel.setText("Master Host/IP address:");
		hostipAddressLabel.setBounds(10, 21, 157, 25);
		connectionPanel.add(hostipAddressLabel);

		final JLabel portNumberLabel = new JLabel();
		portNumberLabel.setText("Master Port number:");
		portNumberLabel.setBounds(10, 52, 117, 25);
		connectionPanel.add(portNumberLabel);

		portNumberTextField = new JTextField();
		portNumberTextField.setText("5668");
		portNumberTextField.setBounds(133, 52, 267, 20);
		connectionPanel.add(portNumberTextField);

		hostNameTextField = new JTextField();
		hostNameTextField.setText("localhost");
		hostNameTextField.setBounds(133, 23, 267, 20);
		connectionPanel.add(hostNameTextField);

		autoTransferCheckBox = new JCheckBox();
		autoTransferCheckBox.setText("Auto transfer project files when project loads");
		autoTransferCheckBox.setBounds(10, 83, 390, 23);
		connectionPanel.add(autoTransferCheckBox);

		final JPanel directoriesPanel = new JPanel();
		directoriesPanel.setBounds(10, 133, 447, 102);
		getContentPane().add(directoriesPanel);
		directoriesPanel.setBorder(new TitledBorder(null, "Directories", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, SystemColor.activeCaption));
		directoriesPanel.setLayout(null);

		projectHomeDirTextField = new JTextField();
		projectHomeDirTextField.setText("c:\\Projects\\Proj1");
		projectHomeDirTextField.setBounds(124, 28, 238, 21);
		directoriesPanel.add(projectHomeDirTextField);

		final JLabel projectNameLabel_1_2 = new JLabel();
		projectNameLabel_1_2.setBounds(27, 26, 91, 24);
		directoriesPanel.add(projectNameLabel_1_2);
		projectNameLabel_1_2.setText("Home Directory:");

		final JButton browseHomeDirButton = new JButton();
		browseHomeDirButton.setBounds(368, 27, 69, 24);
		directoriesPanel.add(browseHomeDirButton);
		browseHomeDirButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				String newPath = getLocation(1);
				if (newPath.equals(""))
					return;
				projectHomeDirTextField.setText(newPath);
			}
		});
		browseHomeDirButton.setText("browse");

		final JLabel outputFileLabel = new JLabel();
		outputFileLabel.setText("Output File:");
		outputFileLabel.setBounds(27, 56, 91, 24);
		directoriesPanel.add(outputFileLabel);

		outputFileTextField = new JTextField();
		outputFileTextField.setText("c:\\Projects\\output\\output.exe");
		outputFileTextField.setBounds(124, 55, 238, 21);
		directoriesPanel.add(outputFileTextField);

		final JButton browseOutputFileButton = new JButton();
		browseOutputFileButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				String newPath = getLocation(0);
				if (newPath.equals(""))
					return;
				outputFileTextField.setText(newPath);
			}
		});
		browseOutputFileButton.setText("browse");
		browseOutputFileButton.setBounds(368, 54, 69, 24);
		directoriesPanel.add(browseOutputFileButton);

		final JButton cancelButton = new JButton();
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				doCancel();
			}
		});
		cancelButton.setText("Cancel");
		cancelButton.setBounds(271, 364, 90, 23);
		getContentPane().add(cancelButton);
		
		m_Client = null;
		initFields();
	}
	
	/**
	 * @return The compilation project
	 */
	public CompilationClient getProject()
	{
		this.setVisible(true);
		return m_Client;

	}
	private CompilationClient m_Client;
	
	/**
	 * A wrapper for the static function SharedComponents.getLocation()
	 * 
	 * @param type - The type of the path to get from the user. 
	 *
	 * @see	JChooser, SharedComponents.getLocation(type,this)
	 * 
	 * @return The path that the usered entered in a JChooser dialog.
	 */
	private String getLocation(int type)
	{
		return SharedComponents.getLocation(type,this);
	}
	
	/**
	 * initialize the dialog's fields.
	 */
	private void initFields()
	{
		try {
			userNameTextField.setText(InetAddress.getLocalHost().getHostName());
		} catch (UnknownHostException e) {
			userNameTextField.setText("MyUserName");
		}
		
	}
	
	/**
	 * closes the window
	 */
	private void doCancel()
	{
		this.dispose();
	}
	
	/**
	 * updates the settings of the new project
	 */
	private void doOK()
	{
		if (!validInput())
			return;
		ClientSettings settings = new ClientSettings();
		settings.username 		= userNameTextField.getText();
		settings.projectName 	= projectNameTextField.getText();
		settings.savePassword	= savepasswordCheckBox.isSelected();
		settings.workingDirectory = projectHomeDirTextField.getText();
		File f = new File(outputFileTextField.getText());
		settings.outputDirectory = f.getParent();
		settings.compFlags.outputFileName = f.getName();
		settings.masterHostName = hostNameTextField.getText();
		settings.masterPort		= Integer.parseInt(portNumberTextField.getText());
		settings.autoTransferFiles = autoTransferCheckBox.isSelected();
		m_Client = new CompilationClient(settings);
		
		settings.password = (settings.savePassword ?
				String.valueOf(passwordTextField.getPassword()) : "");
		this.dispose();
	}
	
	/**
	 * checks if the input is valid, if it's not valid an error window
	 * will be opened.
	 * 
	 * @return true if valid, false otherwise
	 */
	private boolean validInput()
	{
		File f = new File(projectHomeDirTextField.getText());
		LinkedList<EMessageBoxType> errors = new LinkedList<EMessageBoxType>();
		if (userNameTextField.getText().equals(""))
			errors.add(EMessageBoxType.ERROR_MISSING_USERNAME);
		if (projectNameTextField.getText().equals(""))
			errors.add(EMessageBoxType.ERROR_MISSING_PROJECTNAME);
		
		boolean flag = false;
		try { f = new File(projectHomeDirTextField.getText()); }
		catch(Exception e)
		{ flag = true; }
		if (flag || f.isFile() || (!f.exists()))
			errors.add(EMessageBoxType.ERROR_BAD_HOME_DIRECTORY);
		flag = false;
		try
		{
			f = new File(outputFileTextField.getText());
			if (!MYA_File.validFilename(f.getName()))
				flag = true;
			else
			{
				f = new File(f.getParent());
				f.mkdirs();
			}
		}
		catch(Exception e) { flag = true; }
		if(flag)
			errors.add(EMessageBoxType.ERROR_BAD_OUTPUT_FILENAME);
		if (hostNameTextField.getText().equals(""))
			errors.add(EMessageBoxType.ERROR_MISSING_MASTER_HOSTNAME);
		try { Integer.parseInt(portNumberTextField.getText()); }
		catch(Exception e) { errors.add(EMessageBoxType.ERROR_MISSING_PORT_NUMBER); }
		if (errors.size() > 0)
		{
			TextMessages.showMessageBox(errors,null);
			return false;
		}
		return true;
	}
}
